// @author: caoshi
// @date: 2021-05-05 19:22
package test

import (
	"demo01_mysql/src/util"
	"fmt"
)


// 测试插入数据
func InsertOneTest()  {
	db := util.GetDb("demo")
	stmt := util.GetStmt(db, "insert into dept values (?, ?, ?)")

	defer func() {
		if db != nil {
			db.Close()
		}
		if stmt != nil {
			stmt.Close()
		}
	}()

	r, err := stmt.Exec(60, "财务部", "武汉市")
	if err != nil {
		fmt.Println("新增失败")
	}
	fmt.Println("插入数据成功")
	id, err := r.LastInsertId()
	fmt.Println(id)
}

// 测试修改数据
// 注意: 若两次修改的数据相同, 即第二次修改时数据没有任何变化, 那么将不会修改
func ModifyTest()  {
	db := util.GetDb("demo")
	stmt := util.GetStmt(db, "update dept set dname = ?, loc = ? where deptno = ?")

	defer func() {
		if db != nil {
			db.Close()
		}
		if stmt != nil {
			stmt.Close()
		}
	}()

	r, _ := stmt.Exec("财务部门", "湖北省武汉市", 60)
	count, _ := r.RowsAffected()
	if count > 0 {
		fmt.Println("修改成功")
	} else {
		fmt.Println("修改失败")
	}

}


// 测试删除数据
func DeleteTest() {
	db := util.GetDb("demo")
	stmt := util.GetStmt(db, "delete from dept where deptno = ?")

	defer func() {
		if db != nil {
			db.Close()
		}
		if stmt != nil {
			stmt.Close()
		}
	}()

	r, err := stmt.Exec(60)
	if err != nil {
		fmt.Println("删除失败")
	}
	count, err := r.RowsAffected()
	if count > 0 {
		fmt.Println("删除成功")
	} else	{
		fmt.Println("删除失败")
	}

}

func QueryTest() {
	db := util.GetDb("demo")
	stmt, err := db.Prepare("select * from dept")
	if err != nil {
		fmt.Println("预处理失败")
		return
	}
	defer func() {
		if db != nil {
			db.Close()
		}
		if stmt != nil {
			stmt.Close()
		}
	}()

	rows, err := stmt.Query()
	if err != nil {
		fmt.Println("获取结果失败")
	}
	for rows.Next() {
		var deptno int
		var dname, loc string
		err := rows.Scan(&deptno, &dname, &loc)
		if err != nil {
			fmt.Println("读取失败")
		}
		fmt.Println(deptno, " ", dname, " ", loc)
	}


}






